package com.sanchunhui.psc.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.sanchunhui.psc.R
import com.sanchunhui.psc.data.protocol.Company
import org.jetbrains.anko.find


class CompanyDropDownAdapter(private val context: Context, private val list: List<Company>) :
    BaseAdapter() {

    private var checkItemPosition = 0

    fun setCheckItem(position: Int) {
        checkItemPosition = position
        notifyDataSetChanged()
    }

    override fun getCount(): Int {
        return list.size
    }

    override fun getItem(position: Int): Any? {
        return null
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        val viewHolder: ViewHolder
        if (convertView != null) {
            viewHolder = convertView.tag as ViewHolder
        } else {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_list_drop_down, null)
            viewHolder = ViewHolder(convertView)
            convertView!!.tag = viewHolder
        }
        fillValue(position, viewHolder)
        return convertView
    }

    private fun fillValue(position: Int, viewHolder: ViewHolder) {
        val company = list[position]
        viewHolder.mText!!.text = company.name
        if (checkItemPosition != -1) {
            if (checkItemPosition == position) {
                viewHolder.mText!!.setTextColor(context.resources.getColor(R.color.drop_down_selected))
                viewHolder.mText!!.setCompoundDrawablesWithIntrinsicBounds(
                    null,
                    null,
                    context.resources.getDrawable(R.mipmap.drop_down_checked),
                    null
                )
            } else {
                viewHolder.mText!!.setTextColor(context.resources.getColor(R.color.drop_down_unselected))
                viewHolder.mText!!.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
            }
        }
    }

    internal class ViewHolder(view: View) {

        var mText: TextView? = null

        init {
           mText = view.find(R.id.text)
        }
    }
}
